<template>
  <view class="login-container">
    <!-- 背景装饰 -->
    <view class="bg-decoration">
      <view class="circle circle-1"></view>
      <view class="circle circle-2"></view>
      <view class="circle circle-3"></view>
    </view>

    <!-- 内容区域 -->
    <view class="content-wrapper">
      <!-- Logo 和标题 -->
      <view class="header-section">
        <view class="logo-wrapper">
          <image class="logo" src="/static/logo.png" mode="aspectFit"></image>
        </view>
        <text class="app-name">生活记</text>
        <text class="app-slogan">记录生活，分享美好</text>
      </view>

      <!-- 登录卡片 -->
      <view class="login-card">
        <!-- 微信一键登录 -->
        <button class="wechat-login-btn" open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber">
          <view class="btn-content">
            <u-icon name="weixin-fill" color="#fff" size="40"></u-icon>
            <text class="btn-text">微信一键登录</text>
          </view>
        </button>

        <!-- 或者分割线 -->
        <view class="divider">
          <view class="divider-line"></view>
          <text class="divider-text">或</text>
          <view class="divider-line"></view>
        </view>

        <!-- 手机号登录 -->
        <view class="input-group">
          <view class="input-wrapper">
            <text class="input-icon">📱</text>
            <input class="input-field" type="number" v-model="phoneNumber" placeholder="请输入手机号" maxlength="11" />
          </view>

          <view class="input-wrapper">
            <text class="input-icon">🔒</text>
            <input class="input-field" type="number" v-model="verifyCode" placeholder="请输入验证码" maxlength="6" />
            <button class="code-btn" :disabled="codeCountdown > 0" @tap="sendVerifyCode">
              <text class="code-text">{{ codeCountdown > 0 ? `${codeCountdown}s` : '获取验证码' }}</text>
            </button>
          </view>
        </view>

        <!-- 登录按钮 -->
        <button class="login-btn" :class="{ disabled: !canLogin }" :disabled="!canLogin" @tap="onLogin">
          <text class="login-btn-text">登录</text>
        </button>

        <!-- 协议 -->
        <view class="agreement">
          <view class="checkbox-wrapper" @tap="toggleAgreement">
            <view class="checkbox" :class="{ checked: agreedTerms }">
              <text v-if="agreedTerms" class="check-icon">✓</text>
            </view>
            <text class="agreement-text">
              我已阅读并同意
              <text class="link" @tap.stop="viewTerms('user')">《用户协议》</text>
              和
              <text class="link" @tap.stop="viewTerms('privacy')">《隐私政策》</text>
            </text>
          </view>
        </view>
      </view>

      <!-- 底部提示 -->
      <view class="footer-tips">
        <text class="tip-text">首次登录将自动注册账号</text>
        <view class="account-login-link" @tap="goToAccountLogin">
          <text class="link-text">使用账号密码登录</text>
          <text class="arrow">→</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { wechatLogin, phoneLogin, sendSmsCode } from '@/api/auth'
import { useUser } from '@/composables/useUser'

// 获取用户状态管理
const { setLoginInfo } = useUser()

// 表单数据
const phoneNumber = ref('')
const verifyCode = ref('')
const agreedTerms = ref(false)
const codeCountdown = ref(0)

// 是否可以登录
const canLogin = computed(() => {
  return phoneNumber.value.length === 11 &&
    verifyCode.value.length === 6 &&
    agreedTerms.value
})

/**
 * 微信一键登录
 * 流程：
 * 1. 用户点击按钮授权获取手机号
 * 2. 同时调用 wx.login 获取 code
 * 3. 将 code + encryptedData + iv 发送到后端
 * 4. 后端解密并返回用户信息和 Token
 */
const onGetPhoneNumber = async (e: any) => {
  console.log('获取手机号事件:', e)

  // 处理不同的错误情况
  if (e.detail.errMsg !== 'getPhoneNumber:ok') {
    let errorMessage = '获取手机号失败'

    if (e.detail.errMsg === 'getPhoneNumber:fail no permission') {
      errorMessage = '未开启获取手机号权限\n请前往微信小程序管理后台：\n开发 → 接口设置 → 获取手机号\n开启权限（需企业认证）'
    } else if (e.detail.errMsg === 'getPhoneNumber:fail user deny') {
      errorMessage = '用户拒绝授权'
    } else if (e.detail.errMsg.includes('cancel')) {
      errorMessage = '取消授权'
    } else {
      errorMessage = e.detail.errMsg || '获取手机号失败'
    }

    console.error('获取手机号失败:', e.detail.errMsg)

    // 如果是权限问题，使用模态框显示详细说明
    if (e.detail.errMsg === 'getPhoneNumber:fail no permission') {
      uni.showModal({
        title: '权限未开启',
        content: errorMessage,
        showCancel: false,
        confirmText: '我知道了'
      })
    } else {
      uni.showToast({
        title: errorMessage,
        icon: 'none',
        duration: 3000
      })
    }
    return
  }

  // 检查是否同意协议
  if (!agreedTerms.value) {
    uni.showToast({
      title: '请先阅读并同意用户协议和隐私政策',
      icon: 'none'
    })
    return
  }

  try {
    // 1. 调用 wx.login 获取 code
    const loginRes = await new Promise<UniApp.LoginRes>((resolve, reject) => {
      uni.login({
        provider: 'weixin',
        success: resolve,
        fail: reject
      })
    })

    if (!loginRes.code) {
      throw new Error('获取登录凭证失败')
    }

    // 2. 获取用户信息（昵称、头像）
    let userProfile: any = null
    try {
      userProfile = await new Promise((resolve, reject) => {
        uni.getUserProfile({
          desc: '用于完善用户资料',
          success: resolve,
          fail: reject
        })
      })
    } catch (error) {
      console.log('用户取消授权获取用户信息:', error)
      // 如果用户取消授权，继续登录流程，但不传用户信息
    }

    // 3. 调用后端登录接口
    const { encryptedData, iv } = e.detail
    const response = await wechatLogin({
      code: loginRes.code,
      encryptedData,
      iv,
      nickname: userProfile?.userInfo?.nickName,
      avatarUrl: userProfile?.userInfo?.avatarUrl,
      gender: userProfile?.userInfo?.gender
    })

    // 4. 保存用户信息和 Token
    setLoginInfo(response.user, response.accessToken, response.refreshToken)

    // 5. 提示成功并跳转
    uni.showToast({
      title: '登录成功',
      icon: 'success'
    })

    setTimeout(() => {
      uni.switchTab({
        url: '/pages/home/home'
      })
    }, 1500)

  } catch (error: any) {
    console.error('微信登录失败:', error)
    uni.showToast({
      title: error.message || '登录失败，请重试',
      icon: 'none'
    })
  }
}

/**
 * 发送验证码
 */
const sendVerifyCode = async () => {
  // 验证手机号格式
  if (phoneNumber.value.length !== 11) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    })
    return
  }

  // 验证手机号是否为纯数字
  if (!/^1[3-9]\d{9}$/.test(phoneNumber.value)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    })
    return
  }

  try {
    // 调用后端接口发送验证码
    await sendSmsCode(phoneNumber.value)

    uni.showToast({
      title: '验证码已发送',
      icon: 'success'
    })

    // 开始倒计时
    codeCountdown.value = 60
    const timer = setInterval(() => {
      codeCountdown.value--
      if (codeCountdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)

  } catch (error: any) {
    console.error('发送验证码失败:', error)
    // 错误提示已在 request 中处理
  }
}

/**
 * 手机号验证码登录
 */
const onLogin = async () => {
  if (!canLogin.value) return

  // 检查是否同意协议
  if (!agreedTerms.value) {
    uni.showToast({
      title: '请先阅读并同意用户协议和隐私政策',
      icon: 'none'
    })
    return
  }

  try {
    // 调用后端登录接口
    const response = await phoneLogin({
      phone: phoneNumber.value,
      code: verifyCode.value
    })

    // 保存用户信息和 Token
    setLoginInfo(response.user, response.accessToken, response.refreshToken)

    // 提示成功并跳转
    uni.showToast({
      title: '登录成功',
      icon: 'success'
    })

    setTimeout(() => {
      uni.switchTab({
        url: '/pages/accountLogin/accountLogin'
      })
    }, 1500)

  } catch (error: any) {
    console.error('登录失败:', error)
    // 错误提示已在 request 中处理
  }
}

// 切换协议同意状态
const toggleAgreement = () => {
  agreedTerms.value = !agreedTerms.value
}

// 查看协议
const viewTerms = (type: string) => {
  uni.showToast({
    title: `查看${type === 'user' ? '用户协议' : '隐私政策'}`,
    icon: 'none'
  })
}

// 跳转到账号登录页面
const goToAccountLogin = () => {
  uni.navigateTo({
    url: '/pages/accountLogin/accountLogin'
  })
}
</script>

<style scoped>
.login-container {
  width: 100vw;
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
}

/* 背景装饰 */
.bg-decoration {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: hidden;
}

.circle {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
}

.circle-1 {
  width: 400rpx;
  height: 400rpx;
  top: -100rpx;
  right: -100rpx;
}

.circle-2 {
  width: 300rpx;
  height: 300rpx;
  bottom: 100rpx;
  left: -50rpx;
}

.circle-3 {
  width: 200rpx;
  height: 200rpx;
  top: 50%;
  right: 50rpx;
}

/* 内容区域 */
.content-wrapper {
  position: relative;
  z-index: 1;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0 60rpx;
  padding-top: 80rpx;
}

/* 头部 */
.header-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 80rpx;
}

.logo-wrapper {
  width: 160rpx;
  height: 160rpx;
  background: #fff;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 32rpx;
  box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.15);
}

.logo {
  width: 120rpx;
  height: 120rpx;
}

.app-name {
  font-size: 56rpx;
  font-weight: bold;
  color: #fff;
  margin-bottom: 16rpx;
}

.app-slogan {
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.9);
}

/* 登录卡片 */
.login-card {
  width: 100%;
  background: #fff;
  border-radius: 32rpx;
  padding: 60rpx 40rpx;
  box-shadow: 0 20rpx 80rpx rgba(0, 0, 0, 0.15);
}

/* 微信登录按钮 */
.wechat-login-btn {
  width: 100%;
  height: 96rpx;
  background: #07c160;
  border-radius: 48rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 40rpx;
}

.wechat-login-btn::after {
  border: none;
}

.btn-content {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.wechat-icon {
  width: 40rpx;
  height: 40rpx;
}

.btn-text {
  font-size: 32rpx;
  font-weight: 500;
  color: #fff;
}

/* 分割线 */
.divider {
  display: flex;
  align-items: center;
  margin-bottom: 40rpx;
}

.divider-line {
  flex: 1;
  height: 1rpx;
  background-color: #e5e5e5;
}

.divider-text {
  font-size: 24rpx;
  color: #999;
  padding: 0 20rpx;
}

/* 输入框组 */
.input-group {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
  margin-bottom: 40rpx;
}

.input-wrapper {
  display: flex;
  align-items: center;
  height: 96rpx;
  background: #f5f5f5;
  border-radius: 16rpx;
  padding: 0 24rpx;
  gap: 16rpx;
}

.input-icon {
  font-size: 36rpx;
}

.input-field {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.code-btn {
  padding: 12rpx 24rpx;
  background: transparent;
  border: 1rpx solid #4A90E2;
  border-radius: 8rpx;
  font-size: 24rpx;
}

.code-btn::after {
  border: none;
}

.code-btn[disabled] {
  opacity: 0.5;
}

.code-text {
  color: #4A90E2;
  font-size: 24rpx;
}

/* 登录按钮 */
.login-btn {
  width: 100%;
  height: 96rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 48rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 32rpx;
}

.login-btn::after {
  border: none;
}

.login-btn.disabled {
  opacity: 0.5;
}

.login-btn-text {
  font-size: 32rpx;
  font-weight: 500;
  color: #fff;
}

/* 协议 */
.agreement {
  display: flex;
  justify-content: center;
}

.checkbox-wrapper {
  display: flex;
  align-items: flex-start;
  gap: 12rpx;
}

.checkbox {
  width: 32rpx;
  height: 32rpx;
  border: 2rpx solid #ddd;
  border-radius: 6rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  margin-top: 2rpx;
}

.checkbox.checked {
  background: #4A90E2;
  border-color: #4A90E2;
}

.check-icon {
  font-size: 20rpx;
  color: #fff;
  font-weight: bold;
}

.agreement-text {
  font-size: 24rpx;
  color: #666;
  line-height: 1.5;
}

.link {
  color: #4A90E2;
}

/* 底部提示 */
.footer-tips {
  margin-top: 40rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 24rpx;
}

.tip-text {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.8);
}

.account-login-link {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 16rpx 32rpx;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 48rpx;
  backdrop-filter: blur(10rpx);
}

.link-text {
  font-size: 26rpx;
  color: #fff;
  font-weight: 500;
}

.arrow {
  font-size: 28rpx;
  color: #fff;
}
</style>
